﻿const Joi = require("joi");
const express = require('express');
const router = express.Router();

const courses = [
    {id:1,name:'course1'},
    {id:2,name:'course2'},
    {id:3,name:'course3'},
];


router.get('/',(req,res)=>{
    res.send(courses);
});

// route parameters
router.get('/:year/:month',(req,res) =>{
    res.send(req.params);
});

// handling get requests
router.get('/:id',(req,res) =>{
    const course = courses.find(c => c.id === parseInt(req.params.id));
    if(!course){    // 404
        res.status(404).send('The course with the given ID was not found');
        return;
    }
    res.send(course);
});



// handling post requests
router.post('/',(req,res) =>{
    // input validation
    const { error } = validateCourse(req.body); // result.error

    if(error){
        res.status(400).send(error.details[0].message);
        return;
    }


    const course = {
        id:courses.length + 1,
        name:req.body.name
    };
    courses.push(course);
    res.send(course);
});

// handling http put request
router.put('/:id',(req,res) =>{
    const course = courses.find(c => c.id === parseInt(req.params.id));
    if(!course){    // 404
        res.status(404).send('The course with the given ID was not found');
        return;
    }

    const result = validateCourse(req.body);
    const { error } = validateCourse(req.body); // result.error

    if(error){
        res.status(400).send(error.details[0].message);
        return;
    }

    course.name = req.body.name;
    res.send(course);

});


router.delete('/:id',(req,res) => {
    const course = courses.find(c => c.id === parseInt(req.params.id));
    if(!course){    // 404
        res.status(404).send('The course with the given ID was not found');
        return;
    }

    // Delete
    const index = courses.indexOf(course);
    courses.splice(index,1);

    res.send(courses);
});


function validateCourse(course){
    const schema = {
        name:Joi.string().min(3).required()
    };

    return Joi.validate(course,schema);
}

module.exports = router;